package com.zmn.mcc.admin.controller.staff.staffreinstatement;


import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.request.RequestUtil;
import com.zmn.mcc.model.entity.staff.staffreinstatement.StaffReinstatement;
import com.zmn.mcc.services.interfaces.staff.StaffService;
import com.zmn.mcc.services.interfaces.staff.staffreinstatement.StaffReinstatementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Optional;


/**
 * 复职信息表基础修改Controller
 *
 * @author tanghongjun
 * @since 2020-10-22 15:53:17
 */
@RestController
@Slf4j
@RequestMapping("/staff/staffreinstatement")
public class StaffReinstatementModifyController extends StaffReinstatementBaseController {

    @Resource
    private StaffReinstatementService staffReinstatementService;

    @Resource
    private StaffService staffService;

    /**
     * 描述:新增或修改员工复职信息
     *
     * @param staffReinstatement 复职信息相关数据
     * @return 执行结果
     * @auther tanghongjun
     * @since 2020/10/23
     */
    @RequestMapping("/addEdit")
    @RequiresPermissions("/staff/staffreinstatement/addEdit.action")
    public ResponseDTO addEdit(HttpServletRequest request, @RequestBody StaffReinstatement staffReinstatement) {
        Date now = DateUtil.getNow();
        int reinstateId = Optional.ofNullable(staffReinstatement.getReinstateId()).orElse(0);
        String ip = RequestUtil.getRequestIp(request);
        try {
            if (reinstateId == 0) {
                staffReinstatement.setCreater(getStaffName());
                staffReinstatement.setCreateTime(now);
                staffReinstatement.setUpdater(getStaffName());
                staffReinstatement.setUpdateTime(now);
                staffReinstatementService.insert(staffReinstatement);

                // 同步修改员工状态，并将员工账号启用
                staffService.reinstatementStaff(staffReinstatement.getStaffId(), getLoginStaff(), ip);

            } else {
                staffReinstatement.setUpdater(getStaffName());
                staffReinstatement.setUpdateTime(now);
                staffReinstatementService.updateByKey(staffReinstatement);
            }

            return ResponseDTO.success(true, "操作成功！");
        } catch (Exception e) {
            log.error("新增/修改失败, Exception:{}, msg:{}", e, e.getMessage());
            return ResponseDTO.fail("操作失败！");
        }
    }

}
